package com.alvis.media.controller.admin;

import com.alvis.media.base.BaseApiController;
import com.alvis.media.base.RestResponse;
import com.alvis.media.constant.UserConstant;
import com.alvis.media.constant.UserReturnCode;
import com.alvis.media.domain.User;
import com.alvis.media.domain.UserEventLog;
import com.alvis.media.domain.other.KeyValue;
import com.alvis.media.service.AuthenticationService;
import com.alvis.media.service.UserEventLogService;
import com.alvis.media.service.UserService;
import com.alvis.media.utility.DateTimeUtil;
import com.alvis.media.utility.PageInfoHelper;
import com.alvis.media.viewmodel.admin.user.*;
import com.github.pagehelper.PageInfo;
import lombok.AllArgsConstructor;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.UUID;


/**
 * 后台普通用户列表
 */
// @RestController = @Controller + @ResponseBody -> 传输JSON数据
@RestController("AdminUserController")
@RequestMapping(value = "/api/admin/user")
@AllArgsConstructor
public class UserController extends BaseApiController
{
    /**
     * 用户Service
     */
    @Autowired
    private UserService userService;

    /**
     * 普通用户日志Service
     */
    private final UserEventLogService userEventLogService;

    /**
     * 权限Service
     */
    private final AuthenticationService authenticationService;

    /**
     * 用户添加和修改（编辑）
     * @param  model  编辑的条件 -- 用户编号
     * @return RestResponse<User> 响应JSON数据给前台页面
     */
    @RequestMapping(value = "/edit", method = RequestMethod.POST)
    public RestResponse<User> edit(@RequestBody @Valid UserCreateVM model)
    {
        // 将model请求参数（用户在页面中输入的用户信息）转换成User对象
        User user = modelMapper.map(model, User.class);

        if (model.getId() == null) // 添加用户
        {
            User existUser = userService.getUserByUserName(model.getUserName()); // 根据用户名查询用户信息
            if (existUser != null)
            {
                // 在代码中直接数字  属于硬编码
                return new RestResponse<User>(UserReturnCode.USER_ALREADY_EXISTS, "用户已存在");
            }

            if (StringUtils.isBlank(model.getPassword())) // 密码不允许为空 页面中的必填字段都要校验
            {
                return new RestResponse<User>(UserReturnCode.USER_PWD_NOT_ALLOW_NULL, "密码不能为空");
            }

            user.setUserUuid(UUID.randomUUID().toString());
            user.setCreateTime(new Date());
            user.setLastActiveTime(new Date());
            user.setDeleted(false);
            String encodeNewPwd = authenticationService.pwdEncode(model.getPassword());
            user.setPassword(encodeNewPwd);
            userService.insertByFilter(user); // 做入库操作
        }


        if (model.getId() != null) // 编辑用户
        {
            System.out.println("22222222-----------------------------------------------------22222222");
            return RestResponse.ok();
        }
        return RestResponse.ok();
    }


    @RequestMapping(value = "/update", method = RequestMethod.POST)
    public RestResponse update(@RequestBody @Valid UserUpdateVM model) {
        User user = userService.selectById(getCurrentUser().getId());
        modelMapper.map(model,user);
        user.setModifyTime(new Date());
        userService.updateByIdFilter(user);
        return RestResponse.ok();
    }

    /**
     * 启用/禁用代码
     * @param id 要启用/禁用的某条用户记录的主键（用户编号）值 修改T_USER表中status 1-启用  0-禁用
     * @return 响应对应的JSON数据给页面
     */
    @RequestMapping(value = "/changeStatus/{id}", method = RequestMethod.POST)
    public RestResponse<Integer> changeStatus(@PathVariable Integer id)
    {
        //  status 1-启用  0-禁用
        // status == 启用吗 ? 0 : 1;
        User user = userService.getUserById(id);

        Integer newStatus = user.getStatus() == UserConstant.USER_STATUS_ENABLE ? UserConstant.USER_STATUS_DISABLE : UserConstant.USER_STATUS_ENABLE;
        user.setStatus(newStatus); // 修改新的用户状态值
        user.setModifyTime(new Date()); // 更新用户的修改时间
        userService.updateByIdFilter(user); // 做修改用户状态的操作（入库）
        return RestResponse.ok(newStatus); // 把修改后的用户状态发送页面
    }


    /**
     * 删除用户信息（只改数据库表的标记位，不是真的删除数据）
     * @param id 根据普通用户编号去查询用户信息，然后修改用户是否删除的标志位
     * @return RestResponse 删除后的JSON数据
     */
    @RequestMapping(value = "/delete/{id}", method = RequestMethod.POST)
    public RestResponse delete(@PathVariable Integer id)
    {

//        // 根据用户编号查询某个用户信息
//        User user = userService.getUserById(id);
//
//        if (user == null) {
//            return RestResponse.fail(SystemCode.ParameterValidError.getCode(), "用户不存在");
//        }
//
//        // 检查用户是否已经被删除
//        if (user.getDeleted() != null && user.getDeleted()) {
//            return RestResponse.fail(SystemCode.ParameterValidError.getCode(), "用户已被删除");
//        }
//
//        // 使用逻辑删除：设置deleted标志为true
//        user.setDeleted(true);
//        user.setModifyTime(new Date());
//
//        // 执行更新操作
//        int result = userService.updateByIdFilter(user);
//
//        if (result > 0) {
//            return RestResponse.ok(result);
//        } else {
//            return RestResponse.fail(SystemCode.InnerError.getCode(), "删除失败");
//        }

        // 根据用户编号查询某个用户信息
        User user = userService.getUserById(id);

        // 不真正的删除用户信息，而是改用户是否删除的标志位
        user.setDeleted(true);
        
        // 真正的修改是否用户删除的标志位
        int updateOne = userService.updateByIdFilter(user);

        //  int updateOne = userService.deleteById(userId); // NO
        // return RestResponse.ok(updateOne); // NO
        return RestResponse.ok(updateOne);
    }

    /**
     * 查询用户列表方法
     * @param model 查询条件（根据用户名称）
     * @return RestResponse<PageInfo<UserResponseVM>> 带分页的用户信息列表
     */
    @RequestMapping(value = "/page/list", method = RequestMethod.POST)
    public RestResponse<PageInfo<UserResponseVM>> pageList(@RequestBody UserPageRequestVM model) {
        PageInfo<User> pageInfo = userService.userPage(model);
        // PageInfo<User> pageInfo --》转换成 PageInfo<UserResponseVM> page
        // UserResponseVM页面要展示的内容
        PageInfo<UserResponseVM> pageResult = PageInfoHelper.copyMap(pageInfo, d -> UserResponseVM.from(d));
        return RestResponse.ok(pageResult); // 响应JSON数据给前台页面
    }

    /**
     * 日志中心 - 用户日志列表查询方法
     * @param model
     * @return
     */
    @RequestMapping(value = "/event/page/list", method = RequestMethod.POST)
    public RestResponse<PageInfo<UserEventLogVM>> eventPageList(@RequestBody UserEventPageRequestVM model) {
        PageInfo<UserEventLog> pageInfo = userEventLogService.page(model);
        PageInfo<UserEventLogVM> page = PageInfoHelper.copyMap(pageInfo, d -> {
            UserEventLogVM vm = modelMapper.map(d,UserEventLogVM.class);
            vm.setCreateTime(DateTimeUtil.dateFormat(d.getCreateTime()));
            return vm;
        });
        return RestResponse.ok(page);

        //return RestResponse.ok();
    }

    @RequestMapping(value = "/select/{id}", method = RequestMethod.POST)
    public RestResponse<UserResponseVM> select(@PathVariable Integer id) {

        //User user = userService.selectById(id);

        User user = userService.getUserById(id);
        UserResponseVM userVm = UserResponseVM.from(user);
        return RestResponse.ok(userVm);

        //return RestResponse.ok();
    }

    /**
     * 查询当前登录用户信息
     */
    @RequestMapping(value = "/current", method = RequestMethod.POST)
    public RestResponse<UserResponseVM> current() {
        User user = getCurrentUser(); // 获取当前用户信息
        UserResponseVM userVm = UserResponseVM.from(user);
        return RestResponse.ok(userVm);
    }


    @RequestMapping(value = "/selectByUserName", method = RequestMethod.POST)
    public RestResponse<List<KeyValue>> selectByUserName(@RequestBody String userName) {

        if (StringUtils.isEmpty(userName)) {
            return RestResponse.ok(new ArrayList<>());
        }
        User user = userService.getUserByUserName(userName);
        List<KeyValue> result = new ArrayList<>();
        if (user != null) {
            result.add(new KeyValue(user.getId().toString(), user.getUserName()));
        }
        return RestResponse.ok(result);

        //return RestResponse.ok();
    }

    @RequestMapping(value = "/getUserDetailByUserId/{id}", method = RequestMethod.POST)
    public RestResponse<UserResponseVM> getUserDetailByUserId(@PathVariable Integer id) {

        return RestResponse.ok();
    }
}
